﻿package com.kennycosca.util {
	
	import flash.events.*;

	/**
	 * @author kentendo
	 */
	
	
	public class LoaderManager extends EventDispatcher {
		
		public static const START:String = "start";
		public static const READY:String = "ready";
		public static const LOADED:String = "loaded";
		public static const FAILED:String = "failed";
		
		private var _loaders:Array = new Array();
		private var _loadCount:Number = 0;
		
		public function LoaderManager() {
			trace("LoaderManager Constructor");
		}
		
		public function get loadCount():Number {
			return _loadCount;	
		}
		
		public function get loaderTotal():Number {
			return _loaders.length;	
		}
		
		public function addLoader(loader:*, completeHandler:Function = null, failHandler:Function = null):* {
			if (!loader) return;
			if (loaderTotal == 0) dispatchEvent(new Event(START));
			if (completeHandler != null) loader.addEventListener(LOADED, completeHandler);
			if (failHandler != null) loader.addEventListener(FAILED, failHandler);
			loader.addEventListener(LOADED, loadedHandler);
			loader.addEventListener(FAILED, failedHandler);
			_loaders.push(loader);
			return loader;
		}
		
		private function loadedHandler(e:Event):void {
			_loadCount++;
			if (_loadCount == loaderTotal) {
				trace("LoaderManager.loadHandler.READY (" + e.target.url + ") : " + _loadCount + " loaderTotal: " + loaderTotal);
				dispatchEvent(new Event(READY));
			} else {
				trace("LoaderManager.loadHandler.LOADED (" + e.target.url + ") : " + _loadCount + " loaderTotal: " + loaderTotal);
				dispatchEvent(new Event(LOADED));
			}
		}
		
		private function failedHandler(e:Event):void {
			dispatchEvent(new Event(FAILED));	
		}
	}
}
